{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e0615d83",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "fba29427",
   "metadata": {},
   "outputs": [],
   "source": [
    "tab = pd.read_excel('tab_latex.xlsx')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "76f17db3",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 对齐方式c\n",
    "ncol = 'c'*tab.shape[1]\n",
    "\n",
    "# 表头\n",
    "header = '        '\n",
    "for i in range(tab.shape[1]):\n",
    "    header += tab.columns[i]\n",
    "    if i < tab.shape[1] - 1:\n",
    "        header += ' & '\n",
    "    else:\n",
    "        header += ' \\\\\\\\'\n",
    "\n",
    "# 数据\n",
    "tab_data = np.array(tab)\n",
    "\n",
    "data = '        '\n",
    "for i in range(tab.shape[0]):\n",
    "    for j in range(tab.shape[1]):\n",
    "        data += str(tab_data[i,j])\n",
    "        if j < tab.shape[1] - 1:\n",
    "            data += ' & '\n",
    "        else:\n",
    "            data += ' \\\\\\\\\\n'\n",
    "    data += '        '\n",
    "    \n",
    "# 写入文件\n",
    "with open('tab_latex.txt','w+') as tab_latex:\n",
    "    tab_latex.write(\n",
    "            '\\\\begin{table}\\n'\n",
    "            '    \\\\caption{An example table.}\\n'\n",
    "            '    \\\\label{tab:example}\\n'\n",
    "            f'    \\\\begin{{tabular}}{{{ncol}}}\\n'\n",
    "            '        \\\\hline\\n'\n",
    "            f'{header}\\n'\n",
    "            '        \\\\hline\\n'\n",
    "            f'{data}'\n",
    "            '\\\\hline\\n'\n",
    "            '    \\\\end{tabular}\\n'\n",
    "            '\\\\end{table}'\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ccbbee3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
